import {reqCartList,reqDelCarts,reqCheckAll} from '@/api'
const state={
    shoppingTrolley:[]
}
const mutations={
    GETCARTDATALIST(state,result){
        state.shoppingTrolley=result
    }
}
const actions={
    async getCartDataList({commit}){
        let result = await reqCartList()
        if(result.code===200){
            commit('GETCARTDATALIST',result.data)
        }
    },
    //删除 一个
    async getDelCart({commit},skuId){
        let result = await reqDelCarts(skuId)
        if(result.code===200){
            return 'ok'
        }else{
            return Promise.reject(new Error('Del error'))
        }
    },
    async getCheck({commit},{skuId,isChecked}){
        // console.log('isChecked',typeof(isChecked));
        let result = await reqCheckAll(skuId,isChecked)
        // console.log(result);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject(new Error("faile"));
        }
    },
    updateAllChecked({dispatch,state},isChecked){
        let promiseAll = []
        // console.log('state==>',state.shoppingTrolley[0].cartInfoList);
        state.shoppingTrolley[0].cartInfoList.forEach(item => {
            let pormis = dispatch('getCheck',{
                skuId:item.skuId,
                isChecked
            })
            promiseAll.push(pormis)
        });
        return Promise.all(promiseAll)
    },
    //删除选中的所有商品
    DelPitchOnChecked({dispatch,getters}){
        let PromiseAll = []
        getters.shoppingTrolley.cartInfoList.forEach((item)=>{
            let promise = item.isChecked == 1 ? dispatch('getDelCart',item.skuId) : ""
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    }
}
const getters={
    shoppingTrolley(state){
        return state.shoppingTrolley[0] || []
    }
}
export default{
    state,
    mutations,
    actions,
    getters
}